﻿using Apps.Common;
using Apps.Models;
using Apps.Models.PUB;
using Apps.Models.V;
using log4net.Util;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Apps.BLL.LMS
{
    public partial class LMS_TESTDATA_CONFIRMEDBLL
    {
        public DBContainer db = new DBContainer();

        public List<V_LMS_RESULT> GetV_LMS_RESULT(ref GridPager pager, string TestCode="", string queryState="")
        {
            try
            {
                var queryData = db.V_LMS_RESULT.Where(p => (string.IsNullOrEmpty(TestCode) || p.TEST_CODE.Contains(TestCode)) && (string.IsNullOrEmpty(queryState) || p.TEST_STATE_STR.Contains(queryState)));
                pager.totalRows = queryData.Count();
                //排序
                queryData = LinqHelper.SortingAndPaging(queryData, pager.sort, pager.order, pager.page, pager.rows);
                return queryData.ToList();
            }
            catch (Exception ex)
            { 
                throw ex;
            }
        }

        ///// <summary>
        ///// 创建化检批次
        ///// </summary>
        ///// <param name="batch">批次号</param>
        ///// <param name="PSCODE">试样号</param>
        ///// <param name="FDATE">收样日期</param>
        ///// <param name="FSUSER">送样人</param>
        ///// <param name="FUSER">收样人</param>
        ///// <param name="errmsg">返回化验码</param>
        ///// <returns></returns>
        //public void CreateTestBatch(ref GridPager pager, string batch, string PSCODE, string FDATE, string FSUSER, string FUSER,out string errmsg)
        //{
        //    //生成批次信息
        //    string batchcode = CreateTestCode(PSCODE, FDATE, FSUSER, FUSER, out errmsg);
        //    if (string.IsNullOrEmpty(errmsg))
        //    {
        //        db.LMS_COLLECTSAMPLE.Add(new LMS_COLLECTSAMPLE()
        //        {
        //            COLLECT_ID = Guid.NewGuid().ToString("N"),
        //            SAMPLE_ID = PSCODE,
        //            MAKE_CODE = batchcode,
        //            BATCH_CODE = batch,
        //            TEST_CODE = batchcode,
        //            SEND_USER_ID = FUSER,
        //            COLLECT_TIME = DateTime.Now,
        //            COLLECT_USER_ID = FSUSER,
        //            PRINT_COUNT = 0,
        //            MAKE_TYPE = true,
        //        });
        //        return;
        //    }

        //}

        /// <summary>
        /// 获取化检批次
        /// </summary>
        /// <param name="pager"></param>
        /// <param name="indate"></param>
        /// <param name="material"></param>
        /// <param name="supplier"></param>
        /// <param name="transport"></param>
        /// <returns></returns>
        public List<V_LMS_TESTDATA_BATCHModel> GetTestBatch(ref GridPager pager, string batchcode, string indate, string material, string supplier, string transport)
        {
            var queryData = db.V_LMS_TESTDATA_BATCH.Where(p =>
                    (string.IsNullOrEmpty(batchcode) || p.BATCH_CODE.Contains(batchcode)) &&
                    (string.IsNullOrEmpty(material) || p.MATERIEL_ID == material) &&
                    (string.IsNullOrEmpty(supplier) || p.SUPPLIER_ID == supplier) &&
                    (string.IsNullOrEmpty(transport) || p.TRANSPORT_ID == transport)
                );
            pager.totalRows = queryData.Count();
            //排序
            queryData = LinqHelper.SortingAndPaging(queryData, pager.sort, pager.order, pager.page, pager.rows);
            return TransHelper.TransExpList<V_LMS_TESTDATA_BATCH, V_LMS_TESTDATA_BATCHModel>(queryData.ToList());
        }

        /// <summary>
        /// 获取可添加化检的批次信息
        /// </summary>
        /// <param name="pager"></param>
        /// <param name="indate"></param>
        /// <param name="material"></param>
        /// <param name="minename"></param>
        /// <param name="supplier"></param>
        /// <param name="transport"></param>
        /// <returns></returns>
        public List<V_LMS_TESTDATA_ADDBATCHModel> GetBatchCanCreate(ref GridPager pager, string indate, string material, string mine, string supplier, string transport)
        {
            var queryData = db.V_LMS_TESTDATA_ADDBATCH.Where(p =>
                    (string.IsNullOrEmpty(material) || p.MATERIEL_ID == material) &&
                    (string.IsNullOrEmpty(mine) || p.MINE_ID == mine) &&
                    (string.IsNullOrEmpty(supplier) || p.SUPPLIER_ID == supplier) &&
                    (string.IsNullOrEmpty(transport) || p.TRANSPORT_ID == transport)
                );
            pager.totalRows = queryData.Count();
            //排序
            queryData = LinqHelper.SortingAndPaging(queryData, pager.sort, pager.order, pager.page, pager.rows);
            return TransHelper.TransExpList<V_LMS_TESTDATA_ADDBATCH, V_LMS_TESTDATA_ADDBATCHModel>(queryData.ToList());
        }

        ///// <summary>
        ///// 化验号新增
        ///// </summary>
        ///// <param name="PSCODE">试样号</param>
        ///// <param name="FDATE">收样日期</param>
        ///// <param name="FSUSER">送样人</param>
        ///// <param name="FUSER">收样人</param>
        ///// <param name="errmsg">返回化验码</param>
        ///// <returns></returns>
        //private string CreateTestCode(string PSCODE,string FDATE,string FSUSER,string FUSER,out string errmsg)
        //{
        //    var ret = db.ExecuteProduce("PCK_INCREASE_CODE.PROC_INCREASE_HCODE",
        //        db.CreateInParameter("PSCODE", DbType.AnsiString, PSCODE),
        //        db.CreateInParameter("FDATE", DbType.AnsiString, FDATE),
        //        db.CreateInParameter("FSUSER", DbType.AnsiString, FSUSER),
        //        db.CreateInParameter("FUSER", DbType.AnsiString, FUSER),
        //        db.CreateOutParameter("FHCODE", DbType.AnsiString, 10),
        //        db.CreateOutParameter("ERRCODE", DbType.AnsiString, 10),
        //        db.CreateOutParameter("ERRMSG", DbType.AnsiString, 100));
        //    if (ret["ERRCODE"].ToString() == "0")
        //    {
        //        errmsg = string.Empty;
        //        return ret["FHCODE"].ToString();
        //    }
        //    else
        //    {
        //        errmsg = ret["ERRMSG"].ToString();
        //        return string.Empty;
        //    }
        //}

        /// <summary>
        /// 删除化检结果
        /// </summary>
        /// <param name="errors"></param>
        /// <param name="testcode">化验编码或者批次编码（第三方化验时填批次编码）</param>
        /// <returns></returns>
        public bool DeleteTestData(ref ValidationErrors errors, string batchcode)
        {

            try
            {
                if (string.IsNullOrEmpty(batchcode))
                {
                    errors.Add("批次编码不能为空");
                    return false;
                }
                //查询所有的第三方化检结果
                var delItms = from m1 in db.LMS_TESTDATA_CONFIRMED
                              join m2 in db.LMS_COLLECTSAMPLE on m1.TEST_CODE equals m2.TEST_CODE
                              where m2.BATCH_CODE == batchcode && m1.TEST_MODE == 2
                              select m1;
                var items = delItms.ToList();
                //使用批次号、指标编号和录入时间，删除第三方化检结果
                //20180820:第三方化验 不需要单个指标的删除
                //foreach (var item in items)
                if (items.Count > 0)
                {
                    DeleteResult(items[0].TEST_CODE, "", items[0].UPDATE_TIME.Value.ToString("yyyy-MM-dd HH:mm:ss"));
                }
                return true;
            }
            catch (Exception err)
            {
                errors.Add("更新失败" + err.Message);
                return false;
            }
        }

        /// <summary>
        /// 添加并保存化检结果
        /// </summary>
        /// <param name="errors"></param>
        /// <param name="model"></param>
        /// <param name="userid"></param>
        /// <returns></returns>
        public bool Confirmed(ref ValidationErrors errors, List<LMS_TESTDATA_CONFIRMEDModel> model, string testcode, string userid)
        {
            try
            {
                if (model.Count == 0)
                {
                    errors.Add("没有提交任何检验结果");
                    return false;
                }
                using (DBContainer db = new DBContainer())
                {
                    IQueryable<LMS_TESTDATA_CONFIRMED> queryData = db.LMS_TESTDATA_CONFIRMED.AsQueryable<LMS_TESTDATA_CONFIRMED>();
                    var list = queryData.Where(p => p.TEST_CODE == testcode).ToList();

                    foreach (var testResult in model)
                    {
                        InsertResult(testcode, userid, testResult.INDEX_ID, testResult.TEST_VALUE);
                    }
                    return true;
                }
            }
            catch (Exception err)
            {
                errors.Add("更新失败" + err.Message);
                return false;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="testCode"></param>
        /// <param name="testIndex"></param>
        /// <param name="updatetime">格式：yyyy-MM-dd HH24:mi:ss</param>
        /// <returns></returns>
        private bool DeleteResult(string testCode, string testIndex, string updatetime)
        {
            var ret = db.ExecuteProduce("PCK_LMSDATAINFO.DELETE_LMS_CONFIRMEDDATA",
                                    db.CreateInParameter("P_TESTCODE", DbType.AnsiString, testCode),
                                    db.CreateInParameter("P_TESTINDEXS", DbType.AnsiString, testIndex),
                                    db.CreateInParameter("P_UPDATETIME", DbType.AnsiString, updatetime),
                                    db.CreateOutParameter("ERRCODE", DbType.AnsiString, 10),
                                    db.CreateOutParameter("ERRMSG", DbType.AnsiString, 100)
                                    );
            return ret["ERRCODE"].ToString() == "0";
        }

        private bool InsertResult(string testCode, string userid, string testIndex, decimal? testVal)
        {
            var ret = db.ExecuteProduce("PCK_LMSDATAINFO.INSERT_LMS_CONFIRMEDDATA",
                                    db.CreateInParameter("P_TESTCODE", DbType.AnsiString, testCode),
                                    db.CreateInParameter("P_TESTINDEX", DbType.AnsiString, testIndex),
                                    db.CreateInParameter<decimal>("P_TESTVALUE", DbType.Decimal, testVal),
                                    db.CreateInParameter("P_TESTMODE", DbType.AnsiString, 2),//化验方式，0仪器化验 1手工化验 2第三方化验（枚举值LaboratoryTestMode）
                                    db.CreateInParameter("P_STYPE", DbType.AnsiString, 0),//试样类型，0常规样 1非常规样(第三方化验为0)
                                    db.CreateInParameter("P_CTYPE", DbType.AnsiString, 0),//确认类型，0首次化验 1抽样样化验(第三方化验为0)
                                    db.CreateInParameter("P_USERID", DbType.AnsiString, userid),
                                    db.CreateOutParameter("ERRCODE", DbType.AnsiString, 10),
                                    db.CreateOutParameter("ERRMSG", DbType.AnsiString, 100)
                                    );
            return ret["ERRCODE"].ToString() == "0";
        }


        public List<V_LMS_QUERY_RCModel> GetList(ref GridPager pager, string batch,string sample,string lms, string startdate, string enddate, string TYPE_STR = "")
        {
            IQueryable<V_LMS_QUERY_RC> queryData = this.db.V_LMS_QUERY.AsQueryable<V_LMS_QUERY_RC>();
            queryData = queryData.Where(m => m.MAKE_TYPE == 0);
            if (!string.IsNullOrEmpty(batch))
            {
                queryData = queryData.Where(m => m.BATCH_CODE.Contains(batch));
            }
            if (!string.IsNullOrEmpty(sample))
            {
                queryData = queryData.Where(m => m.MAKE_CODE.Contains(sample));
            }
            if (!string.IsNullOrEmpty(lms))
            {
                queryData = queryData.Where(m => m.TEST_CODE.Contains(lms));
            }
            if (!string.IsNullOrEmpty(startdate))
            {
                DateTime dStartDate = DateTime.ParseExact($"{startdate} 00:00:00", "yyyy-MM-dd HH:mm:ss", null);
                queryData = queryData.Where(m => m.MATCH_TIME >= dStartDate);
            }
            //else
            //{
            //    DateTime dStartDate = DateTime.Now.AddDays(-7);
            //    queryData = queryData.Where(m => m.MATCH_TIME >= dStartDate);
            //}
            if (!string.IsNullOrEmpty(enddate))
            {
                //DateTime dEndDate = DateTime.Now.AddDays(1);

                DateTime dEndDate = DateTime.ParseExact($"{enddate} 23:59:59", "yyyy-MM-dd HH:mm:ss", null);
                queryData = queryData.Where(m => m.MATCH_TIME <= dEndDate);
            }
            if (!string.IsNullOrEmpty(TYPE_STR))
            {
                queryData = queryData.Where(m => m.MATERIEL_TYPE_NAME == TYPE_STR);
            }
            pager.totalRows = queryData.Count();
            //排序
            queryData = LinqHelper.SortingAndPaging(queryData, pager.sort, pager.order, pager.page, pager.rows);
            return TransHelper.TransExpList<V_LMS_QUERY_RC, V_LMS_QUERY_RCModel>(queryData.ToList());
        }

        public List<V_LMS_QUERY_RLModel> GetList2(ref GridPager pager, string batch, string startdate, string enddate)
        {
            IQueryable<V_LMS_QUERY_RL> queryData = this.db.V_LMS_QUERY2.AsQueryable<V_LMS_QUERY_RL>();
            if (!string.IsNullOrEmpty(batch))
            {
                queryData = queryData.Where(m => m.BATCH_CODE == batch);
            }
            if (!string.IsNullOrEmpty(startdate))
            {
                DateTime dStartDate = DateTime.ParseExact(startdate, "yyyy-MM-dd", null);
                queryData = queryData.Where(m => m.MATCH_TIME >= dStartDate);
            }
            if (!string.IsNullOrEmpty(enddate))
            {
                DateTime dEndDate = DateTime.ParseExact(enddate, "yyyy-MM-dd", null);
                queryData = queryData.Where(m => m.MATCH_TIME <= dEndDate);
            }
            pager.totalRows = queryData.Count();
            //排序
            queryData = LinqHelper.SortingAndPaging(queryData, pager.sort, pager.order, pager.page, pager.rows);
            return TransHelper.TransExpList<V_LMS_QUERY_RL, V_LMS_QUERY_RLModel>(queryData.ToList());
        }
        public List<V_LMS_TESTDATA_CONFIRMEDModel> GetListDetail(ref GridPager pager, string testCode,string code)
        {
            IQueryable<V_LMS_TESTDATA_CONFIRMED> queryData = this.db.V_LMS_TESTDATA_CONFIRMED.AsQueryable<V_LMS_TESTDATA_CONFIRMED>();
            queryData = queryData.Where(p => (p.TEST_CODE == testCode && p.BATCH_CODE==code) &&
                                             p.STYPE == 0 &&  //试样类型 0常规样 1非常规样
                                             p.TEST_TYPE == 0 && //化验类型 0首次化验 1抽查样化验
                                             p.TEST_MODE != 2 && //化验方式 0仪器化验 1手工化验 2第三方化验
                                             p.TEST_STATE == 1 &&
                                             p.VALUE_SHOW == 1);//结果状态 0化验员确认 1班长审批通过
            pager.totalRows = queryData.Count();
            //排序
            queryData = LinqHelper.SortingAndPaging(queryData, pager.sort, pager.order, pager.page, pager.rows);
            return TransHelper.TransExpList<V_LMS_TESTDATA_CONFIRMED, V_LMS_TESTDATA_CONFIRMEDModel>(queryData.ToList());
        }


        public List<V_LMS_TESTDATA_CONFIRMEDModel> GetConfirmList(ref GridPager pager, string testCode)
        {
            IQueryable<V_LMS_TESTDATA_CONFIRMED> queryData = this.db.V_LMS_TESTDATA_CONFIRMED.AsQueryable<V_LMS_TESTDATA_CONFIRMED>();
            queryData = queryData.Where(p => p.TEST_CODE == testCode &&
                                             p.STYPE == 0 &&  //试样类型 0常规样 1非常规样
                                             p.TEST_MODE != 2 && //化验方式 0仪器化验 1手工化验 2第三方化验
                                             //p.TEST_STATE == 1 &&//结果状态 0化验员确认 1班长审批通过
                                             p.VALUE_SHOW == 1);
            pager.totalRows = queryData.Count();
            //排序
            queryData = LinqHelper.SortingAndPaging(queryData, "INDEX_DISNAME", "ASC", pager.page, pager.rows);
            return TransHelper.TransExpList<V_LMS_TESTDATA_CONFIRMED, V_LMS_TESTDATA_CONFIRMEDModel>(queryData.ToList());
        }
        public List<V_LMS_TESTDATA_RESULTModel> GetTestDataConfirmedDetail(ref GridPager pager, string testCode)
        {
            IQueryable<V_LMS_TESTDATA_RESULT> queryData = m_Rep.Context.V_LMS_TESTDATA_RESULT.AsQueryable<V_LMS_TESTDATA_RESULT>();
            queryData = queryData.Where(p => p.TEST_CODE == testCode);
            pager.totalRows = queryData.Count();
            //排序
            queryData = LinqHelper.SortingAndPaging(queryData, pager.sort, pager.order, pager.page, pager.rows);
            return TransHelper.TransExpList<V_LMS_TESTDATA_RESULT, V_LMS_TESTDATA_RESULTModel>(queryData.ToList());
        }
    }
}
